package com.shuo.dsa.niuke;

/**
 * 难...
 * 在数组中的两个数字，如果前面一个数字大于后面的数字，则这两个数字组成一个逆序对。
 * 输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。即输出P%1000000007
 *      思路: 归并
 */
public class InversePairs {
    private int count = 0;

    public int InversePairs(int[] array) {
        if (array == null || array.length <= 0) return 0;
        mergeUp2Down(array, 0, array.length - 1);
        return count;
    }

    private void mergeUp2Down(int[] a, int start, int end) {
        if (start >= end) return;
        int mid = (end + start) >> 1;
        mergeUp2Down(a, start, mid);
        mergeUp2Down(a, mid + 1, end);
        merge(a, start, mid, end);
    }

    private void merge(int[] a, int start, int mid, int end) {
        int[] temp = new int[end - start + 1];
        int i = start, j = mid + 1, index = 0;
        while (i <= mid && j <= end) {
            if (a[i] > a[j]) {
                temp[index++] = a[j++];
                count += mid - i + 1;
                count = count > 1000000007 ? count % 1000000007 : count;
            } else temp[index++] = a[i++];
        }
        while (i <= mid) temp[index++] = a[i++];
        while (j <= end) temp[index++] = a[j++];
        System.arraycopy(temp, 0, a, start + 0, temp.length);
    }
}
